--Dictado absoluto GPT free.
require "import"
import "java.io.File"
import "cjson"
import "android.content.Context"
import "android.content.Intent"
import "java.util.Locale"
import "android.speech.SpeechRecognizer"
import "android.speech.RecognitionListener"
import "android.speech.RecognizerIntent"
import "android.content.*"
import "android.net.Uri"
import "java.io.File"
import "android.os.Vibrator"
v=function()
local context = activity or service
local vibrator = context.getSystemService(Context.VIBRATOR_SERVICE)
if vibrator.hasVibrator() then
vibrator.vibrate(200)
end
return true
end

service.click({{
"%v$100",
}})

local folderName = "Absoluta by sergiopina/temp"
local folderPath = "/storage/emulated/0/" .. folderName
local folder = File(folderPath)
if not folder.exists() then
local success = folder.mkdirs()
if success then

else
service.asyncSpeak("Nu se poate crea dosarul la: " .. folderPath)
end
end

local basePath = "/storage/emulated/0/Absoluta by sergiopina/temp"
local filePath = basePath .. "/temp.lua"
local file = io.open(filePath, "r")
if not file then
local newFile = io.open(filePath, "w")
if newFile then
local content = [[
Este archivo es únicamente para la marca de agua. Cuando no existe, se crea y una vez creado, evita que la marca de agua vuelva a aparecer.
]]
content = content:gsub("%%%%%%%%+%%%%%%%%+%%%%%%%%+", "")
newFile:write(content)
newFile:close()
else
service.asyncSpeak("nu se poate crea arhiva 'config'. acordați permisiunea de modificare a fișierelor.")
end
else
-- El archivo existe, lo cerramos
file:close()
end
local folderName = "Absoluta by sergiopina/Dictado absoluto GPT Premium"
local folderPath = "/storage/emulated/0/" .. folderName
local folder = File(folderPath)
if not folder.exists() then
local success = folder.mkdirs()
if success then
service.asyncSpeak("API furnizat de Smartprogrammers.")
print("API furnizat de Smartprogrammers.")



else
service.asyncSpeak("Nu se poate crea dosarul la: " .. folderPath)
end
end

--Crear archivo para ejecución externa.--Marcador
local basePath = "/storage/emulated/0/Absoluta by sergiopina/Dictado absoluto GPT Premium"
local filePath = basePath .. "/campana.lua"
local file = io.open(filePath, "r")
if not file then
local newFile = io.open(filePath, "w")
if newFile then
local content = [[
--service.playSoundTick()
]]
content = content:gsub("%%+%%+%%+", "")
newFile:write(content)
newFile:close()
else
service.asyncSpeak("nu se poate crea arhiva 'config'. acordați permisiunea de modificare a fișierelor.")
end
else
-- El archivo existe, lo cerramos
file:close()
end



local basePath = "/storage/emulated/0/Absoluta by sergiopina/Dictado absoluto GPT Premium"
local filePath = basePath .. "/Tabladeeliminacion.lua"
local file = io.open(filePath, "r")
if not file then
local newFile = io.open(filePath, "w")
if newFile then
local content = [[
{
['"'] = '',      -- Elimina todas las comillas dobles del texto.
["'"] = '',      -- Elimina todas las comillas simples del texto.
["texto plano"] = '' -- Elimina todas las ocurrencias de la frase "texto plano".
}
]]
content = content:gsub("%%+%%+%%+", "")
newFile:write(content)
newFile:close()
else
service.asyncSpeak("nu se poate crea arhiva 'config'. acordați permisiunea de modificare a fișierelor.")
end
else
-- El archivo existe, lo cerramos
file:close()
end

local basePath = "/storage/emulated/0/Absoluta by sergiopina/Dictado absoluto GPT Premium"
local filePath = basePath .. "/Puntuacionalfinal.lua"
local file = io.open(filePath, "r")
if not file then
local newFile = io.open(filePath, "w")
if newFile then
local content = [[
]]
content = content:gsub("%%+%%+%%+", "")
newFile:write(content)
newFile:close()
else
service.asyncSpeak("nu se poate crea arhiva 'config'. acordați permisiunea de modificare a fișierelor.")
end
else
-- El archivo existe, lo cerramos
file:close()
end
local basePath = "/storage/emulated/0/Absoluta by sergiopina/Dictado absoluto GPT Premium"
local filePath = basePath .. "/Mayusculaprimeraletra.lua"
local file = io.open(filePath, "r")
if not file then
local newFile = io.open(filePath, "w")
if newFile then
local content = [[
cleanedText = cleanedText:gsub("^%l", string.upper)
]]
content = content:gsub("%%+%%+%%+", "")
newFile:write(content)
newFile:close()
else
service.asyncSpeak("nu se poate crea arhiva 'config'. acordați permisiunea de modificare a fișierelor.")
end
else
-- El archivo existe, lo cerramos
file:close()
end

local basePath = "/storage/emulated/0/Absoluta by sergiopina/Dictado absoluto GPT Premium"
local filePath = basePath .. "/Desactivartabla.lua"
local file = io.open(filePath, "r")
if not file then
local newFile = io.open(filePath, "w")
if newFile then
local content = [[
for key, value in pairs(elementsToRemove) do
cleanedText = cleanedText:gsub(key, value)
end
]]
content = content:gsub("%%+%%+%%+", "")
newFile:write(content)
newFile:close()
else
service.asyncSpeak("nu se poate crea arhiva 'config'. acordați permisiunea de modificare a fișierelor.")
end
else
-- El archivo existe, lo cerramos
file:close()
end
local basePath = "/storage/emulated/0/Absoluta by sergiopina/Dictado absoluto GPT Premium"
local filePath = basePath .. "/Saltodelineaalfinal.lua"
local file = io.open(filePath, "r")
if not file then
local newFile = io.open(filePath, "w")
if newFile then
local content = [[
node = service.getEditText()
service.insert(node, cleanedData .. "\n")
]]
content = content:gsub("%%+%%+%%+", "")
newFile:write(content)
newFile:close()
else
service.asyncSpeak("nu se poate crea arhiva 'config'. acordați permisiunea de modificare a fișierelor.")
end
else
-- El archivo existe, lo cerramos
file:close()
end

local basePath = "/storage/emulated/0/Absoluta by sergiopina/Dictado absoluto GPT Premium"
local filePath = basePath .. "/Instruccionchatbot.lua"
local file = io.open(filePath, "r")
if not file then
local newFile = io.open(filePath, "w")
if newFile then
local content = [[
"Singura ta funcție este să procesezi textul pe care ți-l voi prezenta. După cum urmează: plasează toate semnele de punctuație de care este nevoie. Nu pune niciodată caractere speciale sau comentarii, acesta este textul:"
]]
content = content:gsub("%%+%%+%%+", "")
newFile:write(content)
newFile:close()
else
service.asyncSpeak("nu se poate crea arhiva 'config'. acordați permisiunea de modificare a fișierelor.")
end
else
-- El archivo existe, lo cerramos
file:close()
end

local basePath = "/storage/emulated/0/Absoluta by sergiopina/Dictado absoluto GPT Premium"
local filePath = basePath .. "/ChinoJieshuo.lua"
local file = io.open(filePath, "r")
if not file then
local newFile = io.open(filePath, "w")
if newFile then
local content = [[
cleanedText = cleanedText:gsub("[Cc][Hh][Ii][Nn][Oo]", "Jieshuo")
]]
content = content:gsub("%%+%%+%%+", "")
newFile:write(content)
newFile:close()
else
service.asyncSpeak("nu se poate crea arhiva 'config'. acordați permisiunea de modificare a fișierelor.")
end
else
-- El archivo existe, lo cerramos
file:close()
end


dofile("/storage/emulated/0/Absoluta by sergiopina/Dictado absoluto GPT Premium/campana.lua")


function urlEncode(text)--Marcador
  text = tostring(text)
  text = text:gsub("\n", "\r\n")
  text = text:gsub("([^%w %-%_%.%~])", function(c)
    return string.format("%%%02X", string.byte(c))
  end)
  text = text:gsub(" ", "+")
  return text
end

-- Diccionario de elementos a eliminar
elementsToRemove = 
dofile("/storage/emulated/0/Absoluta by sergiopina/Dictado absoluto GPT Premium/Tabladeeliminacion.lua")

function cleanText(text)
cleanedText = cjson.decode(text)
  if cleanedText then
    cleanedText = cleanedText.result
-- Eliminar elementos no deseados basados en el diccionario
dofile("/storage/emulated/0/Absoluta by sergiopina/Dictado absoluto GPT Premium/Desactivartabla.lua")
-- Capitalizar la primera letra
dofile("/storage/emulated/0/Absoluta by sergiopina/Dictado absoluto GPT Premium/Mayusculaprimeraletra.lua")
-- quitar el punto al final de la línea
dofile("/storage/emulated/0/Absoluta by sergiopina/Dictado absoluto GPT Premium/Puntuacionalfinal.lua")
--Cambiar la palabra chino por la palabra. jieshuo
dofile("/storage/emulated/0/Absoluta by sergiopina/Dictado absoluto GPT Premium/ChinoJieshuo.lua")
    return cleanedText
  else
    return "textul nu este disponibil sau a intervenit o eroare."
  end
end

function hasInternetConnection()
    local connectivityManager = this.getSystemService(Context.CONNECTIVITY_SERVICE)
    local networkInfo = connectivityManager.getActiveNetworkInfo()
    return networkInfo ~= nil and networkInfo.isConnected()
end

function kill()
    if speechRecognizer ~= nil then
        speechRecognizer.destroy()
        speechRecognizer = nil
    end
    return true
end

function startListening()
    if not hasInternetConnection() then
        print("Nu există conexiune la internet. Recunoașterea textului nu este disponibilă.")
        return false
    end
    
    speechRecognizer = SpeechRecognizer.createSpeechRecognizer(this)
    speechListener = RecognitionListener{
        onResults = function(results)
            data = results.getParcelableArrayList(SpeechRecognizer.RESULTS_RECOGNITION)
            if data ~= nil and data.size() > 0 then
                local recognizedText = "Singura ta funcție este să procesezi textul pe care ți-l voi prezenta. După cum urmează: plasează toate semnele de punctuație de care este nevoie. Nu pune niciodată caractere speciale sau comentarii, acesta este textul:" .. "\n" .. data.get(0)
                processRecognizedText(recognizedText)
            end
            kill()
        end,
        onError = function()
            kill()
        end
    }
    
    recognizerIntent = Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH)
    recognizerIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM)
    recognizerIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.getDefault())
    recognizerIntent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE, this.getPackageName())
    speechRecognizer.startListening(recognizerIntent)
    speechRecognizer.setRecognitionListener(speechListener)
    
    return true
end

function processRecognizedText(text)
    local encodedQuestion = urlEncode(text)
    local url = "https://ubsa.in/smartprogrammers/API/gpt/f1.php?question=" .. encodedQuestion
    Http.get(url, function(status, data)
        if status == 200 then
cleanedData = cleanText(data)
task(200, function()
node = service.getEditText()
service.insert(node, cleanedData .. "\n")
end)
            service.speak(cleanedData)
dofile("/storage/emulated/0/Absoluta by sergiopina/Dictado absoluto GPT Premium/campana.lua")
        else
            local errorMessage = "A apărut o eroare în procesarea textului."
            print("Error: " .. errorMessage)
        end
    end)
end

startListening()

if service.click({{
"Trimiteți*|Send*|Signal|Trimite*|POSTEAZĂ|Trim.|Wispr|ok>55",
}})
return true
end


